<?php
/**
 * 阿里云百炼平台qwen-doc-turbo完整示例
 * 1. 上传JSON文件获取file-id
 * 2. 使用file-id调用qwen-doc-turbo模型
 */

// 配置API密钥（请替换为您的实际API密钥）
$apiKey = 'sk-416b931b781c420c9f6331b7346962b5';

// 文件路径
$filePath = __DIR__ . '/test_ingredients.json';

// 检查文件是否存在
if (!file_exists($filePath)) {
    die("文件不存在: $filePath\n");
}

echo "步骤1: 上传JSON文件...\n";

// 1. 上传文件获取file-id
$fileId = uploadFile($apiKey, $filePath);
if (!$fileId) {
    die("文件上传失败\n");
}

echo "文件上传成功，file-id: $fileId\n";

echo "\n步骤2: 调用qwen-doc-turbo模型...\n";

// 2. 使用file-id调用qwen-doc-turbo模型
$dishName = "西红柿炒鸡蛋";
$result = callQwenDocTurbo($apiKey, $fileId, $dishName);

if ($result) {
    echo "模型调用成功:\n";
    echo $result . "\n";
} else {
    echo "模型调用失败\n";
}

/**
 * 上传文件到阿里云百炼平台
 * @param string $apiKey API密钥
 * @param string $filePath 文件路径
 * @return string|false file-id或false
 */
function uploadFile($apiKey, $filePath) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, 'https://dashscope.aliyuncs.com/compatible-mode/v1/files');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $apiKey",
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'file' => new CURLFile($filePath),
        'purpose' => 'file-extract'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $result = json_decode($response, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($result['id'])) {
            return $result['id'];
        }
    }
    
    echo "上传失败，HTTP状态码: $httpCode，响应: $response\n";
    return false;
}

/**
 * 调用qwen-doc-turbo模型
 * @param string $apiKey API密钥
 * @param string $fileId 文件ID
 * @param string $dishName 菜品名称
 * @return string|false 模型返回内容或false
 */
function callQwenDocTurbo($apiKey, $fileId, $dishName) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        "Authorization: Bearer $apiKey",
        'Accept: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    
    // 构造请求数据
    $prompt = "菜品名称：{$dishName} 请根据提供的食材JSON数据，列出上面所需食材及食材所需克重配比。请严格按照JSON中的食材名称进行匹配并获取对应的ID。格式如：鸡蛋：150 西红柿：300 食用油：20 盐：3 白糖：5 葱花：5 水不用列出 请列出烹饪时长，以分钟为节点 如：时长：7 制作步骤： 1、热锅凉油，倒入蛋液，中火煎至底部凝固后翻炒成块，盛出备用 2、锅中补少许油，爆香蒜末/葱白，下西红柿翻炒至出汁 3、加入炒好的鸡蛋，加盐、糖调味，翻炒均匀，可加少量水略焖 4、撒葱花，淋少许生抽（可选），翻炒出锅";
    
    $data = [
        'model' => 'qwen-doc-turbo',
        'input' => [
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'you are a helpful assistant.'
                ],
                [
                    'role' => 'system',
                    'content' => "fileid://$fileId"
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ]
        ],
        'parameters' => [
            'enable_search' => false,
            'incremental_output' => false,
            'result_format' => 'message'
        ]
    ];
    
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        echo "模型调用错误: $error\n";
        return false;
    }
    
    if ($httpCode !== 200) {
        echo "模型调用失败，HTTP状态码: $httpCode，响应: $response\n";
        return false;
    }
    
    $result = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "响应JSON解析失败: " . json_last_error_msg() . "\n";
        return false;
    }
    
    return $result['output']['choices'][0]['message']['content'] ?? false;
}
?>